try
    
% Clear the workspace
close all;
clearvars;
sca;
clear all;

%%
%Prompts
%Prompt for subject number, data & time of run
num_lines = 1;

subprompt = {'Enter participant ID:'};
subdlg_title = 'Participant ID Info';
subjID = inputdlg(subprompt,subdlg_title,num_lines);
subID = subjID{1,1};
sub_num=str2num(subID);

scanprompt = {'Enter scan number:'};
scandlg_title = 'Scan Number';
scan = inputdlg(scanprompt,scandlg_title,num_lines);
scan_num = str2num(scan{1,1});

dateprompt = {'Enter date and time:'};
datedlg_title = 'Date and Time';
datetime = inputdlg(dateprompt,datedlg_title,num_lines);
date = datetime{1,1};

runprompt = {'Enter Run Number:'};
rundlg_title = 'Run Number'; %First run is run 0
cur_run = inputdlg(runprompt,rundlg_title,num_lines);
cur_run = str2num(cur_run{1,1});


%%
%Keyboard setup
invalid=1;
    while invalid
        scanprompt = {'Are you connected to the scanner response box? (y/n)'};
        scandlg_title = 'Scanning (y/n)';
        scanner = inputdlg(scanprompt,scandlg_title,num_lines);
        if strcmp(scanner{1,1},'y')
            scanner=1;
            invalid=0;
        elseif strcmp(scanner{1,1},'n')
            scanner=0;
            invalid=0;
        else
            invalid=1;
        end
    end

    if scanner
        deviceString='Celeritas Dev';%'Serial+Keyboard+Mouse+Joystick';%'Xkeys' %for mgh ;
%             resp_key=30; %for scanner, first button
%             quit_key=20;
%             keys=[30,31,32,33,46];%%button box plus trigger 
    else

        deviceString='Apple Internal Keyboard / Trackpad';%'USB Receiver';%'Apple Keyboard';%'Apple Internal Keyboard / Trackpad';%'Apple Keyboard'=my external keyboard
%             resp_key=30; %1 key, also used to trigger the experiment
%             quit_key=20;%type q to quit at any time
%             keys=[20,30];%need for keyboard
    end
    trigger=46;
    %%%%%%%%%%%%%%%%%%%%%% get device number

    [id,name] = GetKeyboardIndices;
    device=0;
    for i=1:length(name)
      if strcmp(name{i},deviceString)
          device=id(i);
          break;
      end
    end
    if device==0
        error('No device by that name was detected')
    end
    
%% 
%Create a new directory to save this subject's data
dirName = ['CFT_', num2str(subID)];

if scan_num==1

    %create directory to save in to
    if cur_run == 0
    fulldir = fullfile('results', dirName);

    %check to make sure directory doesn't already exist and if it does, request
    %permission to overwrite
    while exist(fulldir,'dir')
        resp = input('File already exists. Would you like to overwrite? y/n:','s');
        while strcmp(resp,'y') ==0 && strcmp(resp,'n') == 0
            resp = input('Invalid response. To overwrite file enter y. To enter new subject number, enter n.','s');
        end

        if (strcmp(resp,'n'))
                subprompt = {'Enter new participant ID:'};
                subdlg_title = 'Participant ID Info';
                num_lines = 1;
                subjID = inputdlg(subprompt,subdlg_title,num_lines);
                subID = subjID{1,1};

                dirName = ['CFT_' num2str(subID)];
                fulldir = fullfile('results', dirName);
        else
            break
        end

    end

    mkdir('results',dirName);
    end

end
    
    
%%
%
Screen('Preference', 'SkipSyncTests', 1);

% Set the screen number to the external secondary monitor if there is one
% connected
screenNumber = max(Screen('Screens'));

% Define black, white and grey
white = WhiteIndex(screenNumber);
black = BlackIndex(screenNumber);

% Open the screen
[w,rect]=Screen('OpenWindow',screenNumber,white);
HideCursor;
ListenChar(2);

% Flip to clear
Screen('Flip', w);

% Query the frame duration
ifi = Screen('GetFlipInterval', w);

% Set the text size and font
Screen('TextSize',w, 30);
Screen('TextFont',w, 'Courier New');
Screen('TextStyle', w, 1);

% Get the centre coordinate of the window
[xCenter, yCenter] = RectCenter(rect);

% Get the screen width and height
screen_w=rect(3);
screen_h=rect(4);

% Set vertical and horizontal margins
%v_margin=50;
%h_margin=((screen_w - (screen_h-(2*v_margin)))/2);

%set the location of the text
%Screen 1
objs_left_sx=(screen_w/4)-100;
objs_right_sx=xCenter+(screen_w/4)-20;
%objs_sy=yCenter+50;
objs_sy=yCenter;
setup_text=yCenter-50;

%set where to wrap the text
wrapat = 74;
wrapat2= 70;

% Query the maximum priority level
topPriorityLevel = MaxPriority(w);

% Set the blend funciton for the screen
Screen('BlendFunction', w, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');

%%
%Load Images and Set Prefs
images.teddy=imread('./images/teddy.jpg','jpg');
images.ring=imread('./images/ring.jpg','jpg');
images.polish=imread('./images/polish.jpg','jpg');
images.axe=imread('./images/axe.jpg','jpg');
%images.filter=imread('./images/filter.jpg','jpg');
images.pole=imread('./images/pole.jpg','jpg');
images.matches=imread('./images/matches.jpg','jpg');

%get image info
img_info = imfinfo('./images/teddy.jpg');

%pull out the image size
img_w = img_info.Width;
img_h = img_info.Height;

%set image locations for objects screen %Left, Top, Right, Bottom
objs_loc_left=[(objs_left_sx),yCenter+50,(objs_left_sx+img_w),(yCenter+img_h)];
objs_loc_center=[(xCenter-.5*img_w),yCenter+50,(xCenter+.5*img_w),(yCenter+img_h)];
objs_loc_right=[(objs_right_sx),yCenter+50,(objs_right_sx+img_w),(yCenter+img_h)];

choice_loc=[(xCenter-.5*img_w),yCenter+75,(xCenter+.5*img_w),(yCenter+img_h+25)];

%%
%Set study parameters
num_trials=14;
num_runs=16;

%set up timing dimensions
wait_text_time=10;
%wait_text_time=1; %for testing
objs_time=4;
choice_time=8;
quest_time=16;
iti=[2,4,6,2,4,6,2];%adjust to be divisible by the number of trials in each run

%load the version matrices
load('vers_params.mat');

%seed random number generator with the current time
rng('shuffle');

if cur_run > 0
    %load the parameters files     
    load (['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_parameters.mat'], 'run_order', 'cond_mat', 'vers_order','low_set','high_set');
    %load existing results files
    if exist (['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_run' num2str(cur_run) '.mat'],'file');
    load (['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_run' num2str(cur_run) '.mat'], 'output_numdata', 'output_celldata', 'tot_trials');
    end


else
    
    %if the subject ID is an even number start with the reject game,
    %otherwise, start with the keep game
    if (mod(sub_num,2)==0)
        game_order=[1,2];
        else game_order=[2,1];%for game numbers: 1=reject, 2=keep
    end

    %an array the length of the number of runs with a 1 for every run that
    %is a reject run and a 2 for every run that is a keep run (alternating)
    run_order=repmat(game_order,1,(num_runs/2));
    
    %generate an array of the version for each run
    %make a matrix of potential version orders
    vers_opts=[1,1,2,2;2,2,1,1;1,2,2,1;2,1,1,2];
    %randomly select one row from this matrix to be this subs order
    row=randi([1,4],1,1);
    this_order=vers_opts(row,:);
    %create an array the length of the number of runs with a 1 for version
    %1 and a 2 for version 2
    vers_order=repmat(this_order,1,(num_runs/4));
    

    %create a matrix where rows are runs and columns are trials with a
    %different value in each cell ranging from 1-num of trials/run.
    for i=1:num_runs
    cond_mat(i,:)=randperm(num_trials);
    end
    
    fixed_low_set={'ring','nail polish','stuffed animal'};
    fixed_high_set={'axe','fishing pole','matches'};
    
    %Here is some neat code I got off of the internet to shuffle cell
    %arrays:
    %Shuffle the low set
    n=numel(fixed_low_set);
    ii=randperm(n);
    [~,previous_order]=sort(ii);
    low_set=fixed_low_set(ii);
    
    %Shuffle the high set
    n=numel(fixed_high_set);
    ii=randperm(n);
    [~,previous_order]=sort(ii);
    high_set=fixed_high_set(ii);
    
    save(['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_parameters.mat'], 'subID','date','run_order','cond_mat','vers_order','low_set','high_set');
    

end


%%
%Begin experiment

%Wait screen
if cur_run==0
if scanner
    preptext = 'You are about to start the task you practiced earlier.\n\nRemember, on every trial you will be asked to respond to the question on a 1-5 scale. To do this you will use the button box in your right hand.\n\n1 = Strongly disagree: Press the button under your thumb\n2 = Somewhat disagree: Press the button under your index finger\n3 = Neutral: Press the button under your middle finger\n4 = Somewhat agree: Press the button under your ring finger\n5 = Strongly agree: Press the button under your pinky\n\nThe first block of trials will begin momentarily.';
else
    preptext = 'You are about to start the task you practiced earlier.\n\nRemember, on every trial you will be asked to respond to the question on a 1-5 scale. To do this you should use the numbers at the top of the keyboard.\n\n1 = Strongly disagree\n2 = Somewhat disagree\n3 = Neutral\n4 = Somewhat agree\n5 = Strongly agree\n\nPress the = to begin.';
end

else
    preptext = 'Please wait. The task will begin again momentarily.';
end

DrawFormattedText(w,preptext,'center','center',black,wrapat2);
Screen('Flip',w);
[keyisdown, secs, keyCode] = KbCheck(device);

%set up trial counter
if cur_run==0
    tot_trials=0;
else
    load (['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_trial_counter.mat'], 'tot_trials');
end
    
%load names.mat-a file with potential names to pull from
load names.mat
%Create a subject specific array of names
names_list=datasample(names,(num_runs*num_trials),'Replace',false);


%run loop
while (cur_run < num_runs)
    keyIsDown=0;
            while ~keyIsDown
                 [keyIsDown, secs, keycode] = KbCheck(device); %check response
                 if ~keycode(trigger)
                     keyIsDown=0;
                 end
                 WaitSecs(.001);
            end
            
        Priority(MaxPriority(w));
        
    run_timer=GetSecs;
     
    trial_time = 0;
    run_total = 0;
    iti_total = 0;

    cur_trial=0;
    
    iti_array=repmat(iti,1,(num_trials/length(iti))); %create an array of possible itis to draw from on each trial. this ensures that each run is the same length
    iti_array=Shuffle(iti_array);
    
    if (cur_run == 0)
        if run_order(cur_run+1)==1
            rej_keep=1;
            waittext = 'You are about to start the first block of trials.\n\nIn this block of trials contestants will be playing the REJECT game.\n\nThis means that each contestant must choose one item from his survival pack to REJECT and leave behind but he gets to KEEP the other two items to bring on to the island.\n\n\n\n\nThe first block of trials will begin in 10 seconds.';
        else
            rej_keep=2;
            waittext = 'You are about to start the first block of trials.\n\nIn this block of trials contestants will be playing the KEEP game.\n\nThis means that each contestant gets to choose one item from his survival pack to KEEP and take on the island but he must REJECT the other two and leave them behind.\n\n\n\n\nThe first block of trials will begin in 10 seconds.';
        end
        
    else
        if run_order(cur_run+1)==1
            rej_keep=1;
            waittext = 'You are about to start the next block of trials.\n\nIn this block of trials contestants will be playing the REJECT game.\n\nThis means that each contestant must choose one item from his survival pack to REJECT and leave behind but he gets to KEEP the other two items to bring on to the island.\n\n\n\n\nThe next block of trials will begin in 10 seconds.';
        else
            rej_keep=2;
            waittext = 'You are about to start the next block of trials.\n\nIn this block of trials contestants will be playing the KEEP game.\n\nThis means that each contestant gets to choose one item from his survival pack to KEEP and take on the island but he must REJECT the other two and leave them behind.\n\n\n\n\nThe next block of trials will begin in 10 seconds.';
        end
    end

        DrawFormattedText(w,waittext,'center','center',black,wrapat2);
        Screen('Flip',w);
        startwaittime=GetSecs;
        while GetSecs-startwaittime<wait_text_time
            WaitSecs(.001);
        end

        cur_run=cur_run + 1;
        
        %identify the parameters version to use with this run
        if vers_order(cur_run)==1
            cur_vers=vers1params;
        else
            cur_vers=vers2params;
        end

        
%Trial loop
while (cur_trial < num_trials)
    %get start time for trial relative to run time
    trial_start_time = GetSecs - run_timer;
            
    %update trial numbers
    tot_trials = tot_trials + 1; %total number of trials in whole experiment
    cur_trial = cur_trial + 1; %total number of trials in current run

    %generate the contestant name for this trial
    cur_name=names_list{tot_trials};
    
%Cal the function to generate the stimuli
[LLH_LHH,rej_num,targ_num,third_num,had_did,pos_neg,rejkeep_low_high,cor_notcor,objs,rej_item,targ_item,third_item,quest_words,quest_item,obj_text,targ_text,quest_text,item_1,item_2,item_3,image_1,image_2,image_3,rej_img] = generate_stim(cond_mat,cur_run,cur_trial,rej_keep,cur_name,images,cur_vers,low_set,high_set);
   

%Screen 1: Display objects
    
    obj_disp_time=GetSecs-run_timer;
    Screen('PutImage',w,image_1,objs_loc_left);
    Screen('PutImage',w,image_2,objs_loc_center);
    Screen('PutImage',w,image_3,objs_loc_right);
    DrawFormattedText(w,obj_text,'center',setup_text,black,wrapat);
    DrawFormattedText(w,item_1,objs_left_sx,objs_sy,black,wrapat);
    DrawFormattedText(w,item_2,'center',objs_sy,black,wrapat);
    DrawFormattedText(w,item_3,objs_right_sx,objs_sy,black,wrapat);
    Screen('Flip', w);
    
        %while (GetSecs - run_timer < objs_time+run_total+iti_total+wait_text_time)
        while (GetSecs - run_timer < objs_time+run_total+iti_total+wait_text_time)
            WaitSecs(.001);
        end

%Screen 2: Display choice
    choice_disp_time=GetSecs-run_timer;
    Screen('PutImage',w,rej_img,choice_loc);
    DrawFormattedText(w,targ_text,'center','center',black,wrapat);
    Screen('Flip', w);
        %while (GetSecs - run_timer < choice_time+run_total+iti_total+wait_text_time)
        while (GetSecs - run_timer < choice_time+run_total+iti_total+wait_text_time)
            WaitSecs(.001);
        end

%Screen 3: Question
qrt = 0;
qresp = 0;
pressed = 0;

%restrict keys to exclude trigger
keys=[30:40];%%all keys on right hand, can be found by running kbdemo
keylist=zeros(1,256);%%create a list of 256 zeros
keylist(keys)=1;

KbQueueCreate(device,keylist);
KbQueueStart(device);

rt_timer = GetSecs;

    quest_disp_time=GetSecs-run_timer;
    DrawFormattedText(w,quest_text,'center','center',black,wrapat);
    Screen('Flip', w);
        %while (GetSecs - run_timer < quest_time+run_total+iti_total+wait_text_time)
        while (GetSecs - run_timer < quest_time+run_total+iti_total+wait_text_time)
            WaitSecs(.001);

            [pressed,keyCode] = KbQueueCheck(device);
            if pressed
                qrt = GetSecs - rt_timer;
                qresp = intersect(30:40, find(keyCode));
            end
        end

KbQueueRelease(device);

    if scanner
            %isolate question responses in scanner
            if qresp == 39
                resp = 1;
            else if qresp == 30
                    resp = 2;
                else if qresp == 31
                        resp = 3;
                    else if qresp == 32
                            resp = 4;
                        else if qresp == 33
                                resp = 5;
                            else resp = NaN;
                            end
                        end
                    end
                end
            end
            
    else
            %isolate question responses on laptop
            if qresp == 30
                resp = 1;
            else if qresp == 31
                    resp = 2;
                else if qresp == 32
                        resp = 3;
                    else if qresp == 33
                            resp = 4;
                        else if qresp == 34
                                resp = 5;
                            else resp = NaN;
                            end
                        end
                    end
                end
            end
    end



            
            
            run_total=run_total+quest_time;
            
            %Set ITI parameters
            iti_this_trial=iti_array(cur_trial);
            iti_total=iti_total+iti_this_trial;
            
            iti_disp_time=GetSecs-run_timer;

            %update output data matrix on each trial for saving
            output_celldata{cur_trial,1} = scan_num;
            output_celldata{cur_trial,2} = cur_run;
            output_celldata{cur_trial,3} = cur_trial;
            output_celldata{cur_trial,4} = objs;
            output_celldata{cur_trial,5} = rej_item;
            output_celldata{cur_trial,6} = targ_item;
            output_celldata{cur_trial,7} = third_item;
            output_celldata{cur_trial,8} = quest_words;
            output_celldata{cur_trial,9} = quest_item;
            output_celldata{cur_trial,10} = quest_text;
            
            output_numdata(cur_trial,1) = scan_num;
            output_numdata(cur_trial,2) = cur_run;
            output_numdata(cur_trial,3) = cur_trial;
            output_numdata(cur_trial,4) = rej_keep;
            output_numdata(cur_trial,5) = vers_order(cur_run);
            output_numdata(cur_trial,6) = cond_mat(cur_run,cur_trial);
            output_numdata(cur_trial,7) = had_did;
            output_numdata(cur_trial,8) = LLH_LHH;
            output_numdata(cur_trial,9) = pos_neg;
            output_numdata(cur_trial,10) = rejkeep_low_high;
            output_numdata(cur_trial,11) = cor_notcor;
            output_numdata(cur_trial,12) = rej_num;
            output_numdata(cur_trial,13) = targ_num;
            output_numdata(cur_trial,14) = third_num;
            output_numdata(cur_trial,15) = iti_this_trial;
            output_numdata(cur_trial,16) = resp;
            output_numdata(cur_trial,17) = qrt;
            output_numdata(cur_trial,18) = obj_disp_time;
            output_numdata(cur_trial,19) = choice_disp_time;
            output_numdata(cur_trial,20) = quest_disp_time;
            output_numdata(cur_trial,21) = iti_disp_time;
            
            DrawFormattedText(w,'+','center','center',black,wrapat);
            Screen('Flip', w);
    
            %while (GetSecs - run_timer < iti_time+run_total+iti_total+wait_text_time)
            while (GetSecs - run_timer < run_total+iti_total+wait_text_time)
                WaitSecs(.001);
            end

            trial_time=GetSecs-run_timer;
            output_numdata(cur_trial,22) = trial_time;



%If it is the last trial of the run, display the between-run rest text.
            rest_timer = GetSecs;

            if (cur_trial == num_trials && cur_run < num_runs)
                    runnum_text = num2str(cur_run);
                    numruns_text = num2str(num_runs);
                    if scanner
                    resttext = ['You have now finished ',runnum_text,' out of ',numruns_text,' blocks of trials.\n\nIf you need to take a break before starting the next block, please do so. \n\nThe next block will begin when you are ready.'];
                    else 
                        resttext = ['You have now finished ',runnum_text,' out of ',numruns_text,' blocks of trials.\n\nIf you need to take a break before starting the next block, please do so. \n\nWhen you are ready to begin the next block, please press the = sign.\n\nIf the next block does not begin immediately, please wait 10 seconds and then press the = sign again.'];
                    end
                    DrawFormattedText(w,resttext,'center','center',black,wrapat2);
                    Screen('Flip',w);
                while GetSecs - rest_timer < 20
                    WaitSecs(.001);
                end

            else if (cur_trial == num_trials && cur_run == num_runs)
                donetext = ['You are now finished with the experiment.\n\nPlease wait and the experimenter will come and get you momentarily.'];
                DrawFormattedText(w,donetext,'center','center',black,wrapat2);
                Screen('Flip',w);
                while GetSecs - rest_timer < 20
                    WaitSecs(.001);
                end


                end
            end

%save output after each trial
save(['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_run' num2str(cur_run) '.mat'], 'output_numdata', 'output_celldata');
save(['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_trial_counter.mat'], 'tot_trials');

             

end

run_time = GetSecs - run_timer; 
save(['~/Desktop/CFT_matlab/results/' dirName '/s' num2str(subID),'_scan',num2str(scan_num),'_run' num2str(cur_run) '.mat'], 'output_numdata', 'output_celldata', 'run_time');

end


catch
    Screen('CloseAll');
    ShowCursor;
    ListenChar(0);
    Priority(0);
    rethrow(lasterror);
end